package com.gxa.eshops.portal.jms;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.eshops.portal.entity.domain.Goods;
import com.gxa.eshops.portal.service.impl.GoodsCacheServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @program: IntelliJ IDEA
 * @description:
 * @author: Mr.Wang
 * @create: 2022-07-12 14:30
 **/
@Component
@Slf4j
public class GoodsCacheListener {
    @Autowired
    RedisTemplate<String ,Object> redisTemplate;
    /**
     * @JmsListener 配置了containerFactory属性,表示通过自定义的容器工厂加载JmsTemplate
     * 该容器工厂配置了事务和签收机制
     * 注入消息的时候,采用消息原本的状态:Message
     * @param session 1
     * @throws JMSException 1
     */
    @JmsListener(destination = "goodsCache",containerFactory = "containerFactory")
    public void deleteGoodsCache(Message message, Session session) throws JMSException {
        log.info("监听器的事务模式:{}",session.getTransacted());
        log.info("监听器的ack签收模式:{}",session.getAcknowledgeMode());
        try {
            //获取message中发送的消息
            Serializable id = ((ActiveMQObjectMessage) message).getObject();
            //删除缓存
            Boolean delete = redisTemplate.delete(GoodsCacheServiceImpl.PRE + id);
            log.info("编号为{}的商品,缓存删除结果:{}",id,delete);
            message.acknowledge();
        } catch (Exception e){
            log.info("签收失败异常:"+e.getMessage());
            //消息签收失败,抛运行时异常 mq就会进行重新发送
            throw new RuntimeException(e);
        }
    }

    @JmsListener(destination = "addHotItem",containerFactory = "containerFactory")
    public void addHotItem(Message message, String goods) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Goods value = objectMapper.readValue(goods, Goods.class);
            Goods readValue = objectMapper.readValue(goods, Goods.class);
            System.out.println("readValue:"+readValue);
            String key = GoodsCacheServiceImpl.PRE+value.getGoodsId();
            Boolean setIfAbsent = redisTemplate.opsForValue().setIfAbsent(key, goods, 24, TimeUnit.HOURS);
            if (Boolean.TRUE.equals(setIfAbsent)) {
                log.info("编号为{}的商品,缓存添加结果:{}",value.getGoodsId(), true);
                message.acknowledge();
            } else {
                log.info("编号为{}的商品,缓存添加结果:{},勿重复添加",value.getGoodsId(), false);
                message.acknowledge();
            }
        } catch (Exception e) {
            log.info("签收失败异常:"+e.getMessage());
            throw new RuntimeException(e);
        }
    }

}
